package Java.utils;

import java.io.*;
import java.util.Objects;
import javax.annotation.Resource;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.SourceDataLine;


public class MusicPlayer {
    private static MusicPlayer instance;//静态实例
    private File file;
    // 是否循环播放
    private volatile boolean isLoop = false;
    // 是否正在播放
    private volatile boolean isPlaying;
    private float newVolumn = 7;
    private InputStream audioStream;

    private PlayThread playThread;

    //私有构造方法
    private MusicPlayer() {
        // 初始化代码
    }
    private MusicPlayer(String resourcePath) {
        audioStream= Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resourcePath),"未找到音频");
    }

    // 公共访问点
    public static synchronized MusicPlayer getInstance() {
        if (instance == null) {
            synchronized (MusicPlayer.class) {
                if (instance == null) {
                    //instance = new MusicPlayer(resourcePath);
                    instance = new MusicPlayer();
                }
            }

        }
        return instance;
    }

    /**
     *播放音乐
     */
    public void play(){
        if(playThread==null||!playThread.isAlive()){
            playThread=new PlayThread();
            playThread.start();
            System.out.println("播放");
        }
    }


    /**
     * 结束音乐（并非暂停）
     */
    public void over() {
        isPlaying = false;
        if (playThread != null) {
            //playThread = null;
            playThread.interrupt();
        }
    }

    /**
     * 设置循环播放
     * @param isLoop
     * @return	返回当前对象
     */
    public MusicPlayer setLoop(boolean isLoop) {
        this.isLoop = isLoop;
        return this;
    }

    /**
     * @param newVolumn
     * @return	返回当前对象
     */
    public MusicPlayer setVolumn(float newVolumn) {
        this.newVolumn = newVolumn;
        return this;
    }

    public synchronized MusicPlayer changePlay(String resourcePath){
//        this.over();
//        audioStream= Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resourcePath),"未找到音频");
//        this.play();
//        return this;
        // 停止当前播放
        if (isPlaying) {
            this.over();
        }

        // 关闭旧的音频流
        if (audioStream != null) {
            try {
                audioStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 设置新的音频流
        audioStream = Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resourcePath), "未找到音频");

        // 开始播放新音乐
        this.play();
        return this;
    }

    /**
     * 异步播放线程
     */
    private class PlayThread extends Thread {
        @Override
        public void run() {
            isPlaying=true;
            try (BufferedInputStream bufIn = new BufferedInputStream(audioStream);
                 AudioInputStream audioIn = AudioSystem.getAudioInputStream(bufIn)) {
                AudioFormat format = audioIn.getFormat();
                SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(format);
                sourceDataLine.open();
                if (newVolumn != 7) {
                    FloatControl control = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
                    control.setValue(newVolumn);
                }
                sourceDataLine.start();
                byte[] buf = new byte[512];
                int len;
                while (isPlaying && (len = audioIn.read(buf)) != -1) {
                    sourceDataLine.write(buf, 0, len);
                }
                sourceDataLine.drain();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //try-with-resources资源自动关闭

            }
        }


    }
}
